package com.woniu.mgr.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu.mgr.controller.form.OrderModifyForm;
import com.woniu.mgr.exception.WebException;
import com.woniu.mgr.exception.WebExceptionCode;
import com.woniu.mgr.model.Account;
import com.woniu.mgr.model.Order;
import com.woniu.mgr.dao.OrderDao;
import com.woniu.mgr.model.OrderLog;
import com.woniu.mgr.service.AccountService;
import com.woniu.mgr.service.OrderLogService;
import com.woniu.mgr.service.OrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.mgr.service.dto.OrderDto;
import com.woniu.mgr.util.BeanCopyUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.websocket.SendResult;
import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * <p>
 * 订单信息表 服务实现类
 * </p>
 *
 * @author Silas
 * @since 2023-02-15
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderDao, Order> implements OrderService {

    @Resource
    private OrderDao orderDao;
    @Resource
    private AccountService accountService;
    @Resource
    private OrderLogService orderLogService;

    @Override
    public IPage<Order> list(Integer page, Integer size) {
        //平台对订单进行分页查询
        Page<Order> page1 = new Page<>(page, size);
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        Page<Order> page2 = orderDao.selectPage(page1, wrapper);
        return page2;
    }

    @Override
    public void orderModify(OrderModifyForm orderModifyForm) {
        //平台修改订单状态为（待支付/已支付待完成/已完成/已取消/退款中/已退款）（账号）
        Order order = BeanCopyUtil.copyObject(orderModifyForm, Order.class);
        updateById(order);
    }


    @Override
    public IPage<Order> query(String condition, Integer page, Integer size) {
        IPage<Order> iPage = new Page<>(page, size);
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        if (!"".equals(condition) || condition != null) {
            wrapper.eq("no", condition)
                    .or().eq("user_name", condition)
                    .or().eq("user_name", condition)
                    .or().eq("coach_name", condition)
                    .or().eq("lesson_name", condition)
                    .or().eq("state", condition)
                    .or().like("create_time", condition);
            IPage<Order> orderIPage = orderDao.selectPage(iPage, wrapper);
            return orderIPage;

        } else {
            IPage<Order> orderIPage = orderDao.selectPage(iPage, wrapper);
            return orderIPage;
        }

    }

    // 同意退款
    @Override
    @Transactional
    public void access(Integer orderId) {
        // 获取顶订单对象
        Order order = this.getById(orderId);
        if(order == null) throw new WebException(WebExceptionCode.ORDER_IS_NOT_EXISTS);
        // 修改订单状态和金额
        order.setState("已退款");
        BigDecimal tempMoney = order.getTempMoney();
        order.setTempMoney(BigDecimal.ZERO);
        // 修改学员账户金额
        Integer userId = order.getUserId();
        Account account = accountService.getById(userId);
        account.setBalance(account.getBalance().add(tempMoney));
        // 更新数据库
        this.updateById(order);
        accountService.updateById(account);
        // 订单日志
        OrderDto orderDto = BeanCopyUtil.copyObject(order, OrderDto.class);
        orderDto.setOperationType("同意退款");
        orderDto.setLogInfo("同意退款");
        OrderLog orderLog = BeanCopyUtil.copyObject(orderDto, OrderLog.class);
        orderLog.setLogTime(LocalDateTime.now());
        orderLogService.save(orderLog);
    }

    // 驳回退款
    @Override
    public void refuse(Integer orderId, String reason) {
        // 获取顶订单对象
        Order order = this.getById(orderId);
        if(order == null) throw new WebException(WebExceptionCode.ORDER_IS_NOT_EXISTS);
        // 修改订单状态
        order.setState("已支付待完成");
        // 更新数据库
        this.updateById(order);
        // 订单日志
        OrderDto orderDto = BeanCopyUtil.copyObject(order, OrderDto.class);
        orderDto.setOperationType("驳回退款申请");
        orderDto.setLogInfo("驳回退款申请："+reason);
        OrderLog orderLog = BeanCopyUtil.copyObject(orderDto, OrderLog.class);
        orderLog.setLogTime(LocalDateTime.now());
        orderLogService.save(orderLog);
    }
}
